package com.bjtu.douyin.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.bjtu.douyin.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OSS oss;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String endpoint;

    public String uploadFile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException("Failed to get input stream from file", e);
        }

        oss.putObject(bucketName, filename, inputStream);
        // 返回文件的URL
        // return oss.generatePresignedUrl(bucketName, filename, new Date(System.currentTimeMillis() + 3600 * 1000)).toString();
        return "http://"+bucketName+"."+endpoint+"/"+filename;
    }

    public InputStream downloadFile(String filename) {
        OSSObject ossObject = oss.getObject(bucketName, filename);
        return ossObject.getObjectContent();
    }

}
